package com.jerry.hm.datastructure.stack;

import java.util.Iterator;

/**
 * 数组实现的栈
 *
 * @author Jerry
 * @since 2024/10/3 18:11
 */
public class ArrayStack<E> implements Stack<E>, Iterable<E> {

    private E[] array;

    /**
     * 栈顶指针，左侧是栈底，右侧是栈顶
     */
    private int top;

    public ArrayStack(int capacity) {
        array = (E[]) new Object[capacity];
    }

    /**
     * 向栈顶压入元素
     *
     * @param e
     * @return
     */
    @Override
    public boolean push(E e) {
        if (isFull()) {
            return false;
        }
        array[top++] = e;
        return true;
    }

    /**
     * 从栈顶弹出元素
     *
     * @return
     */
    @Override
    public E pop() {
        if (isEmpty()) {
            return null;
        }
        E e = array[--top];
        array[top] = null;
        return e;
    }

    /**
     * 获取栈顶的元素
     *
     * @return
     */
    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return array[top - 1];
    }

    /**
     * 栈是否为空
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return top == 0;
    }

    /**
     * 栈是否满
     *
     * @return
     */
    @Override
    public boolean isFull() {
        return top == array.length;
    }

    @Override
    public Iterator<E> iterator() {

        return new Iterator<>() {

            private int cur = top;

            @Override
            public boolean hasNext() {
                return cur > 0;
            }

            @Override
            public E next() {
                return array[--cur];
            }
        };
    }
}
